<template>
    <div class="app-container falseTabel-container">
        <div class="customContainer">
            <el-form :model="saveForm" :inline="true" size="small">
                <el-form-item>
                    {{saveForm.store_name}}
                </el-form-item>
                <el-form-item>
                    <el-select v-model="saveForm.area_id" placeholder="请选择区域" style="width:160px">
                        <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="saveForm.first_type_id" placeholder="请选择一级分类" @change="oneTypeChange"
                        style="width:160px">
                        <el-option v-for="item in oneTypeList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-select v-model="saveForm.type_id" placeholder="请选择二级分类" style="width:160px"
                        @change="towTypeChange">
                        <el-option v-for="item in towTypeList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item class="pull-right">
                    机台总数：{{machine_num}}&#x3000;
                    <el-button type="primary" @click="addMachine">新增机台</el-button>
                </el-form-item>
            </el-form>

            <!-- 列表 -->
            <el-table  highlight-current-row :data="list" v-loading.body="listLoading" border
                size="small">
                <el-table-column align="center" label='机台编号'>
                    <template slot-scope="scope">
                        <el-input onkeypress="return event.which<=57" type="number" onmousewheel="return false;"
                            v-model="scope.row.no" size="small"></el-input>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='刷卡'>
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.trans_id" size="small">
                            <el-option key="0" label="不支持" value="0"></el-option>
                            <el-option key="1" label="支持" value="1"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='出货'>
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.is_unitsshipped" size="small">
                            <el-option key="0" label="不支持" value="0"></el-option>
                            <el-option key="1" label="支持" value="1"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='会员价'>
                    <template slot-scope="scope">
                        <template>
                            <p v-for="item in scope.row.clevice_list" :key="item.id">
                                <el-input onkeypress="return event.which<=57" type="number" onmousewheel="return false;"
                                    min="0" v-model="item.coins_sell_vip" size="small"></el-input>
                            </p>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='非会员价'>
                    <template slot-scope="scope">
                        <template>
                            <p v-for="item in scope.row.clevice_list" :key="item.id">
                                <el-input onkeypress="return event.which<=57" type="number" onmousewheel="return false;"
                                    min="0" v-model="item.coins_sell" size="small"></el-input>
                            </p>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='脉冲数'>
                    <template slot-scope="scope">
                        <template>
                            <p v-for="item in scope.row.clevice_list" :key="item.id">
                                <el-input onkeypress="return event.which<=57" type="number" onmousewheel="return false;"
                                    min="0" v-model="item.pulse" size="small"></el-input>
                            </p>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='扫码套餐'>
                    <template slot-scope="scope">
                        <template>
                            <p v-for="item in scope.row.clevice_list" :key="item.id">
                                <el-select v-model="item.combo_id" size="small">
                                    <el-option v-for="item in package_list" :key="item.id" :label="item.name"
                                        :value="item.id">
                                    </el-option>
                                </el-select>
                            </p>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='关联礼品'>
                    <template slot-scope="scope">
                        <template>
                            <p v-for="item in scope.row.clevice_list" :key="item.id">
                                <el-select v-model="item.is_gift_mapping" size="small">
                                    <el-option key="0" label="不支持" value="0"></el-option>
                                    <el-option key="1" label="支持" value="1"></el-option>
                                </el-select>
                            </p>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='备注'>
                    <template slot-scope="scope">
                        <template>
                            <p v-for="item in scope.row.clevice_list" :key="item.id">
                                <el-input placeholder="选填" size="small" v-model="item.remark"></el-input>
                            </p>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" width="50px">
                    <template slot-scope="scope">
                        <template>
                            <p v-for="item in scope.row.clevice_list" :key="item.id">
                                <el-button :disabled="scope.row.clevice_list.length==1" type="danger"
                                    icon="el-icon-delete" size="mini" @click="delClevice(scope.row.clevice_list,index)">
                                </el-button>
                            </p>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='操作' width="200px">
                    <template slot-scope="scope">
                        <el-button type="danger" size="mini" :disabled="scope.$index==0"
                            @click="delMachine(scope.$index)">删除机台</el-button>
                        <el-button type="primary" size="mini" @click="addClevice(scope.row,scope.$index)">新增卡头
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 自定义底部 -->
        <div class="bottom_box">
            <el-button class="pull-right" type="primary" size="small" @click="saveClick()">保存并返回</el-button>
        </div>
    </div>
</template>

<script>
    import {
        getStore,
        getPage,
        getArea,
        getType,
        save,
        get_area_no,
        batch_create_machine,
    } from "@/api/information/machine_list";
    import {
        get_package,
    } from "@/api/information/deployclevice";
    import { num1to255 } from '@/utils/validate';
    export default {
        data() {
            return {
                machine_num: '',
                towTypeList: [],
                oneTypeList: [],
                areaList: [],
                package_list: [],
                default_no_list: [],
                use_no_list: [],
                listLoading: false,
                default_list: {
                    no: '',
                    trans_id: '',
                    is_unitsshipped: '',
                    clevice_list: [{
                        coins_sell_vip: "",
                        coins_sell: "",
                        pulse: "",
                        remark: "",
                        is_gift_mapping: "",
                        combo_id: ''
                    }]
                },
                list: [],
                saveForm: {
                    brand_id: this.$route.params.brand_id,
                    store_name: '',
                    store_id: this.$route.params.store_id,
                    first_type_id: '',
                    area_id: '',
                    type_id: '',
                    list: []
                },
            };
        },
        created() {
            this.getStoreInfo();
            this.getOneType();
            this.getPackage();
            this.getNum();
            this.fetchData();
        },
        watch: {
            '$route'(to, from) {              
                if (this.$route.params.store_id && this.$route.params.store_id != this.saveForm.store_id || this.$route.params.batch_machine) {
                    this.saveForm.store_id = this.$route.params.store_id;
                    this.fetchData();
                    this.getNo();
                    this.getNum();
                    this.getPackage();
                    this.getStoreInfo();
                }
            }
        },
        methods: {
            // 获取门店信息
            getStoreInfo() {
                getStore({ category_id: 19 }).then(response => {
                    let store_info = response.find((item) => {
                        return item.id === this.$route.params.store_id;
                    })
                    this.saveForm.store_name = store_info.name;
                    this.saveForm.store_id = store_info.id;
                    this.storeChange();
                });
            },

            // 提交
            saveClick() {
                this.saveForm.list = JSON.parse(JSON.stringify(this.list))
                if (!this.saveForm.type_id || !this.saveForm.area_id) {
                    this.$message({ type: 'error', message: '请先选择区域和类型' }, { type: 'warning' });
                    return;
                }
                let ok = true;
                this.saveForm.list.forEach(val => {
                    if (!val.no || !val.trans_id || !val.is_unitsshipped) {
                        ok = false;
                        return false;
                    }
                    val.clevice_list.forEach(val2 => {
                        if (!num1to255(val2.coins_sell) || !num1to255(val2.coins_sell_vip) || !num1to255(val2.pulse) || !val2.is_gift_mapping || !val2.combo_id) {
                            ok = false;
                            return false;
                        }
                    });
                });
                if (!ok) {
                    this.$message({ type: 'error', message: '请将所有信息填写完整,价格和脉冲数为1-255整数' });
                    return;
                }
                this.$confirm('确认保存并返回', '提示').then(() => {
                    batch_create_machine(this.saveForm).then(response => {
                        this.$message({ type: response.code == 1 ? 'success' : 'error', message: response.message });
                        if (response.code == 1) {
                            this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
                                this.$router.push({
                                    name: 'information/machine_list',
                                    params: {
                                        brand_id: this.saveForm.brand_id,
                                        name: this.saveForm.store_id,
                                        routerflag: 1
                                    },
                                })
                            })
                        }
                    });
                })
            },
            getPackage() {
                get_package({ all: 1, brand_id: this.saveForm.brand_id }).then(response => {
                    response.unshift({ id: '0', name: '不支持' });
                    this.package_list = response
                });
            },
            storeChange() {
                this.saveForm.area_id = '';
                getArea({ sid: this.saveForm.store_id }).then(response => {
                    this.areaList = response
                    this.saveForm.area_id = response[0].id;
                })
            },
            getOneType() {
                getType({}).then(response => {
                    this.oneTypeList = response;
                });
            },
            oneTypeChange() {
                this.saveForm.type_id = '';
                getType({ id: this.saveForm.first_type_id }).then(response => {
                    this.towTypeList = response
                })
            },
            towTypeChange() {
                this.getNo();
            },
            getNo() {
                if (!this.saveForm.type_id || !this.saveForm.area_id) {
                    return;
                }
                get_area_no({ type_id: this.saveForm.type_id, area_id: this.saveForm.area_id }).then(response => {
                    let max_no = Math.max.apply(null, response) < 0 ? 0 : Math.max.apply(null, response);
                    this.use_no_list = response;
                    this.default_no_list = [];
                    for (let i = 1; i < max_no + 31; i++) { //最大同时添加30台
                        if (this.use_no_list.indexOf(i + '') == -1) {
                            this.default_no_list.push(i + '')
                        }
                    }
                    this.list.map((item, i) => {
                        return item.no = this.default_no_list[i]
                    })
                })
            },
            defaultNo() {
                let useNo = this.list.map(item => {
                    return item.no
                })
                let usableNo = this.default_no_list.filter(item => {
                    return useNo.indexOf(item) == -1;
                })
                this.list[this.list.length - 1].no = usableNo[0]
            },
            addMachine() {
                if (!this.saveForm.type_id || !this.saveForm.area_id) {
                    this.$message({ type: 'error', message: '请先选择区域和类型' });
                    return;
                }
                if (this.list.length == 30) {
                    this.$message({ type: 'error', message: '单次批量增加机台不能超过30台' });
                    return;
                }
                this.list.push(JSON.parse(JSON.stringify(this.list[this.list.length - 1])))
                this.defaultNo()
            },
            addClevice(row, index) {
                row.clevice_list.push(JSON.parse(JSON.stringify(row.clevice_list[row.clevice_list.length - 1])))
            },
            delMachine(index) {
                this.list.splice(index, 1);
            },
            delClevice(list, index) {
                list.splice(index, 1);
            },
            getNum() {
                getPage({ brand_id: this.saveForm.brand_id, name: this.saveForm.store_id }).then(response => {
                    this.machine_num = response.total
                })
            },
            // 列表获取
            fetchData() {
                this.list = [];
                this.list.push(JSON.parse(JSON.stringify(this.default_list)))
            },
        }
    };
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .el-table {
        margin: 0;

        .el-input {
            max-width: 100px ;
        }
    }
</style>